package kadledav.adventure.framework.builder.name;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import kadledav.adventure.framework.model.general.ActionObject;
import kadledav.adventure.framework.model.world.Item;
import kadledav.adventure.framework.model.world.impl.ItemBasic;

class SimpleNameItem extends ItemBasic {

	private Map<String, NewItemMessenger> possibleInteractions = new HashMap<String, NewItemMessenger>();
	private List<NewItemMessenger> newItemsOnAction = new LinkedList<NewItemMessenger>();
	
	public SimpleNameItem(String name, String description,boolean takeable) {
		super(name, description,takeable);
	}

	public boolean addPossibleInteractions(String nameOfObjectToInteract, SimpleNameItem simpleNameItem, String evolutionInfo) {
		if (possibleInteractions.get(nameOfObjectToInteract) != null) {
			return false;
		}
		possibleInteractions.put(nameOfObjectToInteract, new NewItemMessenger(simpleNameItem, evolutionInfo));
		return true;
	}

	public void addNewItemOnAction(SimpleNameItem newItem, String actionInfo) {
		newItemsOnAction.add(new NewItemMessenger(newItem, actionInfo));
	}

	@Override
	public String doActionWith(ActionObject actionItem, List<Item> inventory) {
		if (actionItem == null) {
			return null;
		}

		NewItemMessenger newItem = possibleInteractions.get(actionItem.getName());
		if (newItem == null) {
			return null;
		}
		inventory.add(newItem.getNewItem());
		inventory.remove(actionItem);
		inventory.remove(this);

		if (newItem.getNewItemInfo() != null) {
			return newItem.getNewItemInfo();
		} else {
			return getName() + " + " + actionItem.getName() + " = " + newItem.getNewItem();
		}
	}

	public String doAction(List<Item> inventory) {
		if(newItemsOnAction.isEmpty()){
			return null;
		}
		StringBuilder result = new StringBuilder();
		StringBuilder newItemNames = new StringBuilder();
		for (NewItemMessenger itemMessenger : newItemsOnAction) {
			inventory.add(itemMessenger.getNewItem());
			result.append((itemMessenger.getNewItemInfo()==null?"":itemMessenger.getNewItemInfo()));
			newItemNames.append(", "+itemMessenger.getNewItem().getName());
		}
		inventory.remove(this);
		String resultString = result.toString();
		if(resultString.isEmpty()){
			return "Nove veci v inventari:"+newItemNames.toString().substring(1);
		}else{
			return resultString;
		}
	}
}

class NewItemMessenger {
	SimpleNameItem newItem;
	String info;

	public NewItemMessenger(SimpleNameItem newItem, String info) {
		super();
		this.newItem = newItem;
		this.info = info;
	}

	public SimpleNameItem getNewItem() {
		return newItem;
	}

	public String getNewItemInfo() {
		return info;
	}
}